<?php

chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";



class SaleOfTheMonth extends IPlugin 
{
    function SaleOfTheMonth($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
    }
    
    function getPluginTag() { return "saleofthemonth"; }
    function getPluginName() { return "Sale of the month Plugin"; }
    function getPluginVersion() { return "1.0.0"; }
    
    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuBlockTitle", "MenuTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Sale of the month"; } break;
            case "MenuTitle" : { return "Sale of the month"; } break;
        };
        return $result;
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------

    function doAction($params)
    {
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;
        }
        
        switch ($_GET["event"])
        {
            case "MakeSalesOfTheMonth": {
             //debug($_GET,"get");  debug($_POST,"post"); 
                if($_GET["pid"]>0)
                {
                    $core = &getCoreInstance();
                    $db = $core->getProperty("db");
                    if($db->getOne("select count(*) from settings where `s_key` like '%saleofthemonth%'")>0)
                    {
                        $db->Exec("update settings set `s_value`='{$_GET[pid]}' where `s_key` like '%saleofthemonth%'");
                    }
                    else
                    {
                        $db->Exec("insert into settings(`s_key`, `s_value`) values ('saleofthemonth', '{$_GET[pid]}')");
                    }
                }
            } break;

            default:
            break;
        }

        $core = &getCoreInstance();
        return true;
    }


    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function Render($params)
    {
        global $_G;
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }
        
        $core = &getCoreInstance();
        $db = $core->getProperty("db");
        $framework = $core->getProperty("framework");
        $render = $framework->smarty;

        $page = "";

        switch ($_G["page"]) {
            default:
                $page = $this->renderSaleOfTheMonthPage($core, $render, $db);
                break;
        }

        return $render->fetch("file:".$this->tplfolder."/".$page);
    }
    
    
    // ----------------------------------------------------------------------------------
    // --- [ Generate Customers List ] --------------------------------------------------
    // ----------------------------------------------------------------------------------

    function cb_renderProducts($data)
    {
        $catalogid = $_GET['id'];
        $img_small = $data["img_small"];
        if( isne($img_small))
        {
            $img_small = "<img src='/inventory/{$img_small}' border=0 />";
        }
        else 
        {
            $img_small = "No Image";
        }
        $dt = array(
                array($data["catalog_id"] , "align=\"center\""),
                array($img_small , ""),
                array( $data["title"], ""),
                array('Y'==$data["is_active"]?"Yes":"No" , "align='center'"),
                array("\$".$data["price"], "align='center'"),
                array("<a href=\"?".$this->getURL()."&id={$catalogid}&pid={$data[catalog_id]}&event=MakeSalesOfTheMonth\">Set as Sale of the month</a>" , "align=\"center\"")
                );
        return $dt;
    }



    function renderSaleOfTheMonthPage(&$core, &$render, &$db)
    {
        $ctglist = array();
        getAllHistory(0, "", $ctglist);
        $render->assign("categorieslist", $ctglist);
        $render->assign("categoryid", $_GET["id"]);
        
        $z = $db->getAll("select * from settings where `s_key` like '%saleofthemonth%'");
        
        //debug($_GET);
        if(count($z) && $z[0]['s_value']>0)
        {
            $z = $db->getAll("select * from catalog where catalog_id={$z[0][s_value]}");
            //debug($z);
            if(count($z))
            {
                $z = $z[0];
                $hs = &$core->getSnippet("historylinks");
                $params = array(
                        "startfrom" => $_GET["id"],
                        "f_id" => "catalog_id",
                        "f_parent" => "parent_id",
                        "f_title" => "title",
                        "table" => "catalog",
                        "stopval" => 0, // root
                        "url" => "",    // ### will be replaced by id
                        "html_root" => "Root",
                        "html_url" => "",
                        "html_separatop" => " :: ",
                        );

                $res = array(
                        "id" => $z["catalog_id"],
                        "history" => $hs->Render($params),
                        "title" => $z["title"],
                        "image" => $z["img_small"],
                    );
                $render->assign("sotm", $res);
            }
        }
        //debug($_GET);
        $curent_catalog_id = 0;
        if($_GET["id"]>0)
        {
            $curent_catalog_id = $_GET["id"];
        }
        $page = $ppg = 0;
        $pg = &$core->getSnippet("paginator");
        $params = array(
                    "cb_class" => &$this,
                    "cb_func" => cb_renderProducts,
                    "urlbase" => $this->getURL()."&id=$curent_catalog_id",
                    "caption" => "Products list",
                    "emptymsg" => "No products collected yet",
                    "header" => array("ID","Image", "Title", "Active", "Price", "Action"),
                    "items" => "",
                    "source" => "sql", // -- sql, array
                    "sql_items" => "select catalog_id,title,is_active,img_small,our_price as price from catalog where is_category = 'N' and parent_id='".$curent_catalog_id."' order by sibling",
                    "sql_count" => "select count(*) from catalog where is_category= 'N' and parent_id='".$curent_catalog_id."'",
                    "ippg" => 5, // -- items per page
                    "nppv" => 5, // -- number pages per view
                    "page" => &$page,
                    "ppg" => &$ppg,
                    );

        $render->assign("products", $pg->Render($params));

        return "saleofthemonth.tpl.php";
    }
};


?>